//
//  AppDelegate.m
//  HWZB
//
//  Created by 许成雄 on 2017/4/13.
//  Copyright © 2017年 wonders. All rights reserved.
//

#import "AppDelegate.h"
#import "MyTabBarController.h"
#import "LoginViewController.h"
#import "Context.h"
#import "HWZBAPIRequest.h"
#import "CommonKit.h"

@interface AppDelegate ()

@property (strong, nonatomic) MyTabBarController *myTabBarController;
@property (strong, nonatomic) UINavigationController *loginNavigationController;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.window.backgroundColor = I_COLOR_WHITE;
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    [[UINavigationBar appearance] setBarTintColor:I_COLOR_WHITE];
    [[UINavigationBar appearance] setBackgroundColor:I_COLOR_WHITE];
    [[UINavigationBar appearance] setTintColor:I_COLOR_RED];
    [[UIBarButtonItem appearanceWhenContainedIn:[UINavigationBar class], nil] setTintColor:I_COLOR_RED];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:17.0f], NSForegroundColorAttributeName:I_COLOR_RED}];
    
    [self showMainViewController];
    
    //获取字典数据
    [self getDictionaryData];
    
    return YES;
}

// sharedDelegate
+ (id)sharedDelegate {
    return (AppDelegate*)[UIApplication sharedApplication].delegate;
}

- (void)showMainViewController {
    if(!self.myTabBarController) {
        self.myTabBarController = [[MyTabBarController alloc] init];
    }
    self.myTabBarController.selectedIndex = 0;
    self.window.rootViewController = self.myTabBarController;
    
    BOOL hasLogin = [[Context sharedInstance] isLogin];
    if(!hasLogin) {
        LoginViewController *loginViewController = [[LoginViewController alloc] init];
        self.loginNavigationController = [[UINavigationController alloc] initWithRootViewController:loginViewController];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.myTabBarController presentViewController:self.loginNavigationController animated:YES completion:^{
            }];
        });
    }
}

- (void)showLoginViewController {
    if(!self.loginNavigationController) {
        LoginViewController *loginViewController = [[LoginViewController alloc] init];
        self.loginNavigationController = [[UINavigationController alloc] initWithRootViewController:loginViewController];
    }
    //TODO
    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.myTabBarController presentViewController:self.loginNavigationController animated:YES completion:^{
//            
//        }];
        [[self getCurrentViewController] presentViewController:self.loginNavigationController animated:YES completion:^{
            
        }];
    });
}
// sharedDelegate

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationUserLogin object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationRefreshOrder object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationAccountInfoChange object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNotificationUserInfoModify object:nil];
}


- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    return YES;
}

- (BOOL)application:(UIApplication *)application openURL:(nonnull NSURL *)url options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    return YES;
}

- (void)getDictionaryData {
    NSString *path = (NSString *)[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *addressFileName = [path stringByAppendingPathComponent:@"address.plist"];
    NSFileManager *manager = [NSFileManager defaultManager];
    if(![manager fileExistsAtPath:addressFileName]) {
        //获取地址字典数据
        [[HWZBAPIRequest sharedInstance] getAddressDictWithParams:nil success:^(NSArray *provinceArray) {
            if(provinceArray != nil) {
                //存储到文件中
                [self saveAddressToPlist:provinceArray];
            }
        } failure:^(NSError *error) {
            NSLog(@"%@", [error localizedDescription]);
        }];

    }
    
    NSString *bankFileName = [path stringByAppendingPathComponent:@"bank.plist"];
    if(![manager fileExistsAtPath:bankFileName]) {
        [[HWZBAPIRequest sharedInstance] getBankDictWithParams:nil success:^(NSArray *bankArray) {
            if(bankArray != nil) {
                //存储到文件中
                [self saveBankToPlist:bankArray];
            }
        } failure:^(NSError *error) {
            NSLog(@"%@", [error localizedDescription]);
        }];
    }
    
    NSString *commodityFileName = [path stringByAppendingPathComponent:@"commodity.plist"];
    if(![manager fileExistsAtPath:commodityFileName]) {
        [[HWZBAPIRequest sharedInstance] getCommodityTypeDictWithParams:nil success:^(NSArray *typeArray) {
            if(typeArray != nil) {
                //存储到文件中
                [self saveCommodityTypeToPlist:typeArray];
            }
        } failure:^(NSError *error) {
            NSLog(@"%@", [error localizedDescription]);
        }];
    }
    
}

- (void)saveAddressToPlist:(NSArray *)proviceArray {
    NSString *path = (NSString *)[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fileName = [path stringByAppendingPathComponent:@"address.plist"];
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager createFileAtPath:fileName contents:nil attributes:nil];
    NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:0];
    for(int i = 0, n = (int)proviceArray.count; i < n; i++) {
        ProvinceInfo *provinceInfo = (ProvinceInfo *)[proviceArray objectAtIndex:i];
        NSDictionary *provinceDict = [CommonKit getObjectData:provinceInfo];
        [tempArray addObject:provinceDict];
    }
    [tempArray writeToFile:fileName atomically:YES];
}

- (void)saveBankToPlist:(NSArray *)bankArray {
    NSString *path = (NSString *)[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fileName = [path stringByAppendingPathComponent:@"bank.plist"];
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager createFileAtPath:fileName contents:nil attributes:nil];
    NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:0];
    for(int i = 0, n = (int)bankArray.count; i < n; i++) {
        BankInfo *bankInfo = (BankInfo *)[bankArray objectAtIndex:i];
        NSDictionary *bankDict = [CommonKit getObjectData:bankInfo];
        [tempArray addObject:bankDict];
    }
    [tempArray writeToFile:fileName atomically:YES];
}

- (void)saveCommodityTypeToPlist:(NSArray *)typeArray {
    NSString *path = (NSString *)[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *fileName = [path stringByAppendingPathComponent:@"commodity.plist"];
    NSFileManager *manager = [NSFileManager defaultManager];
    [manager createFileAtPath:fileName contents:nil attributes:nil];
    NSMutableArray *tempArray = [NSMutableArray arrayWithCapacity:0];
    for(int i = 0, n = (int)typeArray.count; i < n; i++) {
        CommodityTypeInfo *typeInfo = (CommodityTypeInfo *)[typeArray objectAtIndex:i];
        NSDictionary *typeDict = [CommonKit getObjectData:typeInfo];
        [tempArray addObject:typeDict];
    }
    [tempArray writeToFile:fileName atomically:YES];
}


- (UIViewController *)getCurrentViewController {
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    //app默认windowLevel是UIWindowLevelNormal，如果不是，找到UIWindowLevelNormal的
    if(window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows) {
            if(tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    id nextResponder = nil;
    UIViewController *appRootVC=window.rootViewController;
    //如果是present上来的appRootVC.presentedViewController 不为nil
    if(appRootVC.presentedViewController) {
        nextResponder = appRootVC.presentedViewController;
    } else {
        if([window subviews] != nil && [window subviews].count > 0) {
            UIView *frontView = [[window subviews] objectAtIndex:0];
            nextResponder = [frontView nextResponder];
        }
    }
    
    if([nextResponder isKindOfClass:[UITabBarController class]]) {
        UITabBarController * tabbar = (UITabBarController *)nextResponder;
        UINavigationController * nav = (UINavigationController *)tabbar.viewControllers[tabbar.selectedIndex];
        //        UINavigationController * nav = tabbar.selectedViewController ; 上下两种写法都行
        result=nav.childViewControllers.lastObject;
        
    } else if([nextResponder isKindOfClass:[UINavigationController class]]){
        UIViewController * nav = (UIViewController *)nextResponder;
        result = nav.childViewControllers.lastObject;
    } else {
        result = nextResponder;
    }
    
    return result;
}

@end
